<template>
    <div>
        <t-header></t-header>
        <t-cat @setCurrentIndexCat="setCurrentIndexCat($event)"></t-cat>
        <el-alert
        title="当前网站图片资源过多服务器采用的是1Mbps，请耐心等待，如遇图片一直在加载的情况，刷新即可"
        type="info"
        center
        show-icon>
        </el-alert>
        <img-list></img-list>

    </div>
</template>

<script>
import Header from '../components/global/Header';
import Cat from '../components/global/Cat';
import ImgList from '../components/global/ImgList';
import axios from 'axios';
import { onMounted, ref, provide, inject, watch } from '@vue/composition-api';
export default {
    components: {
        't-header': Header,
        't-cat': Cat,
        'img-list': ImgList
    },
    setup(props, context) {
        axios.defaults.baseURL = 'http://47.105.157.158:3000';

        onMounted( () => {
            getCatList();
            currentCatIndex();
        });

        

        // 分类
        const catList = ref('');
        // 获取分类
        const getCatList = async function () {
            let { data: res } = await axios.get('/get/cat');
            if (res.status != 200)
                return context.parent.$message.error('获取分类列表失败，请刷新后重试');
            catList.value = res.cat;
        }

        // 把分类数组传递给子组件
        provide('cat', catList);

        // 当前分类数据参数，默认是全部
        const currentCatData = ref('all');
        // 存储当前分类数据
        const currentData = ref('');
        // 根据当前分类获取对应的数据
        const currentCatIndex = async function () {
            let { data: res } = await axios.get(`/get/cat/img/${currentCatData.value}`);
            if (res.status != 200)
                return context.parent.$message.error('获取分类数据失败，请刷新后重试');
            currentData.value = res.imgs;
        }
        // 把当前分类数据传递给子组件
        provide('currentData', currentData);


        // 接受子组件传递过来的当前索引值，重新渲染图片内容
        const setCurrentIndexCat = async function (e) {
            
            if (e != 999) {
                currentCatData.value = catList.value[e];
            } else {
                currentCatData.value = 'all';
            }
            // 加载效果
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            setTimeout(() => {
              loading.close();
              currentCatIndex();
            }, 2000);            
        }


        const methods = { currentCatIndex, setCurrentIndexCat }

        return {
            ...methods,
            catList
        }
    }
}
</script>

